const db = require("../config/mysql");
const dayjs = require('dayjs');

class OutboundModel {
  constructor() {
    this.db = db;
  }
  async getgoodsinfo(name) {
    // 获取商品信息
    const sql = 'SELECT goods_id,code,goods_pic,cate_id,specification,unit,supplier_id,status,created_at,updated_at FROM goods WHERE name LIKE ?';
    const goods_name = name || '';
    try {
      const [result] = await this.db.query(sql, ['%' + goods_name + '%']);
      return result;
    } catch (error) {
      console.error('查询商品信息失败:', error);
      throw error;
    }
  }
  async getOutboundList(params) {
    // 出库列表查询
    const page = parseInt(params.page) || 1;
    const page_size = parseInt(params.page_size) || 5;
    const code = params.code || '';

    const stall_id = params.stall_id || '';
    const status = params.status || '';
    const out_time = params.out_time || '';
    const procurement = params.procurement || '';
    const purpose = params.purpose || '';
    // 计算偏移量，确保页码有效
    const offset = Math.max(0, (page - 1) * page_size);

    // 构建基础查询条件（用于计数查询）
    let countSql = 'SELECT COUNT(*) as total FROM inventoryout WHERE 1=1';
    let dataSql = 'SELECT * FROM inventoryout WHERE 1=1';
    const queryParams = [];

    // 动态添加搜索条件，避免不必要的通配符搜索
    if (code) {
      const codeCondition = ' AND code LIKE ?';
      countSql += codeCondition;
      dataSql += codeCondition;
      queryParams.push('%' + code + '%');
    }
    if (purpose) {
      const purposeCondition = ' AND purpose LIKE ?';
      countSql += purposeCondition;
      dataSql += purposeCondition;
      queryParams.push('%' + purpose + '%');
    }
    if (stall_id) {
      const stallCondition = ' AND stall_id LIKE ?';
      countSql += stallCondition;
      dataSql += stallCondition;
      queryParams.push('%' + stall_id + '%');
    }
    if (status) {
      const statusCondition = ' AND status = ?';
      countSql += statusCondition;
      dataSql += statusCondition;
      queryParams.push(status);
    }
    // 当传入入库订单号时，先查询inventoryin表获取对应的in_id
    if (procurement) {
      const inSql = 'SELECT in_id FROM inventoryin WHERE code = ?';
      const [inResult] = await this.db.query(inSql, [procurement]);
      if (inResult && inResult.length > 0) {
        const foundInId = inResult[0].in_id;
        // 直接使用in_id作为条件查询出库主表
        const inIdCondition = ' AND in_id = ?';
        countSql += inIdCondition;
        dataSql += inIdCondition;
        queryParams.push(foundInId);
      } else {
        // 如果找不到对应的入库记录，添加条件让结果为空
        countSql += ' AND 1=0';
        dataSql += ' AND 1=0';
      }
    }
    if (out_time) {
      const timeCondition = ' AND out_time LIKE ?';
      countSql += timeCondition;
      dataSql += timeCondition;
      queryParams.push('%' + out_time + '%');
    }
    
    // 添加排序和分页到数据查询
    dataSql += ' ORDER BY out_time DESC LIMIT ? OFFSET ?';
    const dataQueryParams = [...queryParams, page_size, offset];

    try {
      // 并行执行总数查询和数据查询
      const [[countResult], [dataResult]] = await Promise.all([
        this.db.query(countSql, queryParams),
        this.db.query(dataSql, dataQueryParams)
      ]);

      const total = countResult[0].total;
      const total_pages = Math.ceil(total / page_size);

      // 获取所有in_id用于关联查询inventoryin表
      const inIds = dataResult.map(item => item.in_id).filter(id => id);
      let inventoryinData = {};
      let goodsOrderData = {};

      if (inIds.length > 0) {
        const inIdPlaceholders = inIds.map(() => '?').join(',');
        const inventoryinSql = `SELECT in_id, code, in_date, order_id, in_type, in_amount, status, deliverer_name, deliverer_phone, receiver_uid, house_uid, finance_uid, notes, created_at, updated_at, in_doc_pic FROM inventoryin WHERE in_id IN (${inIdPlaceholders})`;
        const [inventoryinResult] = await this.db.query(inventoryinSql, inIds);

        // 构建in_id到入库信息的映射
        inventoryinData = inventoryinResult.reduce((map, item) => {
          map[item.in_id] = item;
          return map;
        }, {});

        // 提取inventoryin表中的order_id字段，用于查询goods_order表
        const orderIds = inventoryinResult
          .map(item => item.order_id)
          .filter(orderId => orderId && orderId !== null && orderId !== undefined);

        if (orderIds.length > 0) {
          const orderIdPlaceholders = orderIds.map(() => '?').join(',');
          const goodsOrderSql = `SELECT * FROM goods_order WHERE order_id IN (${orderIdPlaceholders})`;
          const [goodsOrderResult] = await this.db.query(goodsOrderSql, orderIds);

          // 构建order_id到商品订单信息的映射
          goodsOrderData = goodsOrderResult.reduce((map, item) => {
            map[item.order_id] = item;
            return map;
          }, {});
        }
      }

      // 获取所有stall_id用于关联查询stall表
      const stallIds = dataResult.map(item => item.stall_id).filter(id => id);
      let stallData = {};

      if (stallIds.length > 0) {
        const stallIdPlaceholders = stallIds.map(() => '?').join(',');
        const stallSql = `SELECT * FROM stall WHERE stall_id IN (${stallIdPlaceholders})`;
        const [stallResult] = await this.db.query(stallSql, stallIds);

        // 构建stall_id到摊位信息的映射
        stallData = stallResult.reduce((map, item) => {
          map[item.stall_id] = item;
          return map;
        }, {});
      }

      // 获取所有handler_uid用于关联查询user表
      const handlerUids = dataResult.map(item => item.handler_uid).filter(user_id => user_id);
      let userData = {};

      if (handlerUids.length > 0) {
        const handlerUidPlaceholders = handlerUids.map(() => '?').join(',');
        const userSql = `SELECT * FROM user WHERE user_id IN (${handlerUidPlaceholders})`;
        const [userResult] = await this.db.query(userSql, handlerUids);

        // 构建handler_uid到用户信息的映射
        userData = userResult.reduce((map, item) => {
          map[item.user_id] = item;
          return map;
        }, {});
      }

      // 合并出库数据和对应的入库信息、摊位信息、用户信息、商品订单信息
      const mergedData = dataResult.map(outboundItem => {
        const inventoryinInfo = inventoryinData[outboundItem.in_id] || null;
        return {
          ...outboundItem,
          inventoryinInfo: inventoryinInfo,
          stallInfo: stallData[outboundItem.stall_id] || null,
          handlerInfo: userData[outboundItem.handler_uid],
          // 添加商品订单信息，通过inventoryinInfo中的order_id关联
          goodsOrderInfo: inventoryinInfo && inventoryinInfo.order_id ?
            (goodsOrderData[inventoryinInfo.order_id] || null) : null
        };
      });

      // 返回包含分页信息和合并数据的完整对象
      return {
        data: mergedData,           // 当前页数据（包含入库信息）
        pagination: {
          current_page: page,        // 当前页码
          page_size: page_size,      // 每页数量
          total: total,              // 总记录数
          total_pages: total_pages,  // 总页数
          has_next: page < total_pages,  // 是否有下一页
          has_prev: page > 1         // 是否有上一页
        }
      };
    } catch (error) {
      console.error('查询出库记录失败:', error);
      throw error;
    }
  }




  // 添加出库记录
  async addOutbound(body) {
    console.log("🚚 新增出库参数:", body)

    // 获取outboundDetails参数，并确保它是数组类型
    let outboundDetails = body.outboundDetails;
    if (!Array.isArray(outboundDetails)) {
      console.warn('outboundDetails不是数组类型，设为空数组');
      outboundDetails = [];
    }

    // 检查outboundDetails数组长度
    console.log("outboundDetails数组长度:", outboundDetails.length);

    if (outboundDetails.length === 0) {
      throw new Error('outboundDetails数组不能为空');
    }

    // 遍历 outboundDetails，进一步解构 goodsInfo
    const parsedDetails = outboundDetails.map(item => {
      // 解构出 goodsInfo 对象
      const { goodsInfo, ...rest } = item;

      // 如果 goodsInfo 是字符串形式的 "[object Object]"，尝试解析
      let parsedGoodsInfo = goodsInfo;
      if (typeof goodsInfo === 'string' && goodsInfo.includes('[object Object]')) {
        try {
          // 尝试从字符串中提取 JSON 部分（如果有）
          const jsonStr = goodsInfo.replace(/\[object Object\]/g, '{}');
          parsedGoodsInfo = JSON.parse(jsonStr);
        } catch (e) {
          console.warn('goodsInfo 解析失败，使用空对象:', e.message);
          parsedGoodsInfo = {};
        }
      } else if (typeof goodsInfo === 'object' && goodsInfo !== null) {
        // 如果已经是对象，直接使用
        parsedGoodsInfo = goodsInfo;
      } else {
        // 其他情况，使用空对象
        parsedGoodsInfo = {};
      }

      return {
        ...rest,
        goodsInfo: parsedGoodsInfo
      };
    });

    // 使用解析后的数据替换原始 outboundDetails
    const processedOutboundDetails = parsedDetails;

    // 调试：显示 goodsInfo 结构化前后的对比
    console.log('🔍 goodsInfo 结构化处理对比:');
    outboundDetails.forEach((original, index) => {
      const processed = processedOutboundDetails[index];
      console.log(`第${index + 1}项:`);
      console.log('  原始 goodsInfo:', original.goodsInfo);
      console.log('  结构化 goodsInfo:', processed.goodsInfo);
      console.log('  goodsInfo 类型:', typeof processed.goodsInfo);
    });

    // 时间相关变量
    const currentTime = dayjs().format('YYYY-MM-DD HH:mm:ss');

    // 在body对象中可以直接取到的参数
    // const order_id = body.order_id || null; // 数据库表中没有order_id字段，移除
    // const out_type = body.out_type || 1; // 默认为1-正常出库
    const stall_id = body.stall_id;
    const house_uid = body.house_uid || null;
    const purpose = body.purpose || 1; // 默认为1-正常出库
    const handler_uid = body.handler_uid;
    const receiver_uid = body.receiver_uid || null;
    const approval_uid = body.approval_uid || null;
    const notes = body.notes || '';
    const status = 1; // 默认为1-待审核
    const out_doc_pic = body.out_doc_pic || '';
    const order_item = body.order_item || currentTime;
    const receiver_name = body.receiver_name || '';
    const receiver_phone = body.receiver_phone || '';
    const finance_uid = body.finance_uid || null;
    const total_amount = body.total_amount || 0;
    // 提取商品明细列表
    const items = body.items || [];
    console.log("出库商品明细数量:", items.length);

    // 构建主出库单SQL
    const mainSql = 'INSERT INTO inventoryout (code, out_time, in_id, purpose, total_amount, receiver_uid, handler_uid, house_uid, approver_uid, notes, created_at, updated_at, out_doc_pic, stall_id) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)';

    try {
      // 开启事务
      await this.db.query('START TRANSACTION');
      console.log('✅ 事务已开启');

      // 出库编号：OUT+时间戳（确保唯一性）
      const code = "OUT" + currentTime.replace(/[- :]/g, '').substring(0, 14);
      
      // 从第一个明细项或body中获取in_id（如果没有则使用默认值null）
      const in_id = processedOutboundDetails[0]?.in_id || null;
      
      // 从第一个明细项或body中获取house_id（如果没有则使用默认值null）
      const house_id = (processedOutboundDetails[0]?.house || processedOutboundDetails[0]?.house_id) || house_uid || null;
      
      // 构建主表参数
      const mainParams = [
        code,                                    // code
        order_item,                              // out_time
        in_id,                                   // in_id
        purpose,                                 // purpose
        total_amount,                            // total_amount
        receiver_uid,                            // receiver_uid
        handler_uid,                             // handler_uid
        house_uid,                               // house_uid
        approval_uid,                            // approver_uid
        notes,                                   // notes
        currentTime,                             // created_at
        currentTime,                             // updated_at
        out_doc_pic,                             // out_doc_pic
        stall_id                                 // stall_id
      ];

      console.log("出库主单参数:", mainParams);

      // 插入主出库单（只插入一条记录）
      const [mainResult] = await this.db.query(mainSql, mainParams);
      const out_id = mainResult.insertId;
      console.log("主出库单插入成功，out_id:", out_id);

      // 保存主记录信息
      const mainRecord = {
        out_id: out_id,  // 添加out_id字段，确保后续能正确获取
        in_id: in_id,
        code: code,
        area_id: processedOutboundDetails[0]?.area_id || 1,
        house_id: house_id,
        total_amount: total_amount,
        approver_uid: approval_uid,
        status: status,
        receiver_name: receiver_name,
        receiver_phone: receiver_phone,
        handler_uid: handler_uid,
        house_uid: house_uid,
        finance_uid: finance_uid,
        notes: notes,
        stall_id: stall_id,
        created_at: currentTime,
        updated_at: currentTime
      };

      // 处理商品明细 - 直接处理processedOutboundDetails中的每个商品项
      const itemResults = [];
      console.log('开始处理商品明细，明细数量:', processedOutboundDetails.length);
      console.log('processedOutboundDetails:', JSON.stringify(processedOutboundDetails, null, 2));

      for (let i = 0; i < processedOutboundDetails.length; i++) {
        const detail = processedOutboundDetails[i];

        console.log(`🔍 处理第${i + 1}个商品明细:`, detail);
        console.log(`   对应的主记录out_id:`, mainRecord.out_id);
        console.log(`   即将调用addOutboundDetail方法...`);

        // 准备商品明细参数 - 使用结构化后的 goodsInfo
        const itemParams = {
          out_id: mainRecord.out_id,  // 传递主表生成的out_id
          in_id: detail.in_id || null,
          goods_id: detail.goods_id,
          unit: detail.unit || detail.goodsInfo?.unit || '',
          price: detail.unit_price || detail.goodsInfo?.out_price || 0,
          quantity: Math.max(parseFloat(detail.diff || detail.out_count || detail.quantity || 0), 1),  // 确保出库数量至少为1
          amount: detail.amount || detail.subtotal || 0,
          area_id: detail.house_area || detail.area_id || 1,
          notes: detail.notes || mainRecord.notes || '',
          house_id: detail.house || mainRecord.house_id,
          status: 1,
          user_id: handler_uid,
          // related_order: order_id, // 移除order_id，数据库表中没有这个字段
          inventory_log_notes: detail.notes || mainRecord.notes || ''
        };

        console.log('📦 出库子表参数:', itemParams);
        console.log("⚡ 正在调用 addOutboundDetail...");
        // 调用addOutboundDetail处理单个商品项
        const itemResult = await this.addOutboundDetail(itemParams);
        console.log("✅ addOutboundDetail 执行完成");

        itemResults.push({
          ...itemResult,
          main_out_id: mainRecord.out_id,
          main_code: mainRecord.code
        });
      }

      // 提交事务
      await this.db.query('COMMIT');
      console.log('✅ 事务已提交');

      // 返回完整的出库信息
      return {
        success: true,
        message: "成功创建1条出库单",
        mainRecord: mainRecord,
        mainRecords: [mainRecord],
        itemCount: itemResults.length,
        itemResults: itemResults,
        totalMainRecords: 1
      };

    } catch (error) {
      // 发生错误时回滚事务
      await this.db.query('ROLLBACK');
      console.error('❌ 新增出库失败:', error.message);
      throw new Error(`出库操作失败: ${error.message}`);
    }
  }

  async deleteOutbound(out_id) {
    // 删除出库记录
    const sql = 'UPDATE inventoryout SET status = 9 WHERE out_id = ?';
    try {
      const [result] = await this.db.query(sql, [out_id]);
      return result;
    } catch (error) {
      console.error('删除出库记录失败:', error);
      throw error;
    }
  }
  async GetupdateOutbound(out_id) {
    // 获取出库记录
    const sql = 'SELECT in_id,stall_id,purpose,out_time,total_amount,status,handler_uid,receiver_uid,approver_uid,house_uid,out_doc_pic,notes,created_at,updated_at FROM inventoryout WHERE out_id = ?';
    try {
      const [result] = await this.db.query(sql, out_id);
      return result;
    } catch (error) {
      console.error('获取出库记录失败:', error);
      throw error;
    }
  }


  // 编辑出库记录
  async updateOutbound(out_id, params) {
    // 初始化SQL基础部分和参数数组
    let sql = 'UPDATE inventoryout SET ';
    const queryParams = [];
    const setClauses = [];

    // 动态添加需要更新的字段
    if (params.in_id !== undefined) {
      setClauses.push('in_id = ?');
      queryParams.push(params.in_id);
    }
    if (params.stall_id !== undefined) {
      setClauses.push('stall_id = ?');
      queryParams.push(params.stall_id);
    }
    if (params.purpose !== undefined) {
      setClauses.push('purpose = ?');
      queryParams.push(params.purpose);
    }
    if (params.out_doc_pic !== undefined) {
      setClauses.push('out_doc_pic = ?');
      queryParams.push(params.out_doc_pic || null);
    }
    if (params.total_amount !== undefined) {
      setClauses.push('total_amount = ?');
      queryParams.push(params.total_amount);
    }
    if (params.status !== undefined) {
      setClauses.push('status = ?');
      queryParams.push(params.status);
    }
    if (params.handler_uid !== undefined) {
      setClauses.push('handler_uid = ?');
      queryParams.push(params.handler_uid);
    }
    if (params.receiver_uid !== undefined) {
      setClauses.push('receiver_uid = ?');
      queryParams.push(params.receiver_uid);
    }
    if (params.approver_uid !== undefined) {
      setClauses.push('approver_uid = ?');
      queryParams.push(params.approver_uid);
    }
    if (params.notes !== undefined) {
      setClauses.push('notes = ?');
      queryParams.push(params.notes);
    }
    if (params.house_uid !== undefined) {
      setClauses.push('house_uid = ?');
      queryParams.push(params.house_uid);
    }

    // 强制更新时间字段
    const currentTime = dayjs().format('YYYY-MM-DD HH:mm:ss');
    setClauses.push('updated_at = ?');
    queryParams.push(currentTime);

    // 拼接SET子句和WHERE条件
    sql += setClauses.join(', ') + ' WHERE out_id = ?';
    queryParams.push(out_id); // 添加WHERE条件的参数
    console.log(sql, queryParams);
    try {
      const [result] = await this.db.query(sql, queryParams);
      return result;
    } catch (error) {
      console.error('更新出库记录失败:', error);
      throw error;
    }
  }

  async getgoodsinfoitem(goods_id) {
    // 获取商品信息
    const sql = 'SELECT item_id,in_price,in_count,subtotal,goods_id,inid,unit,house_id,area_id,production_date,expiration_date,supplier_id,is_out,actual_storage,total_remaining,notes,status FROM inventoryinitem WHERE goods_id = ? ORDER BY item_id DESC LIMIT 1';
    try {
      const [result] = await this.db.query(sql, goods_id);
      return result;
    } catch (error) {
      console.error('获取商品信息失败:', error);
      throw error;
    }
  }
  
  async addOutboundDetail(params) {
    console.log('📦 开始添加出库明细，参数:', params);

    // 参数验证
    if (!params) {
      throw new Error('出库明细参数不能为空');
    }

    // 解构参数，设置默认值
    const {
      out_id,
      in_id,
      goods_id,
      unit = '',
      price = 0,
      quantity,
      amount,
      house_id,
      area_id = 1,
      notes = '',
      user_id,
      balance = 0,
      related_order,
      inventory_log_notes = ''
    } = params;

    // 必填参数验证
    if (!out_id) {
      throw new Error('出库单ID不能为空');
    }
    if (!goods_id) {
      throw new Error('商品ID不能为空');
    }
    if (!quantity || quantity <= 0) {
      throw new Error('出库数量必须大于0');
    }
    if (!house_id) {
      throw new Error('仓库ID不能为空');
    }

    // 计算金额（如果没有提供amount）
    const calculated_amount = amount !== undefined ? amount : (quantity * price);
    const currentTime = dayjs().format('YYYY-MM-DD HH:mm:ss');

    try {
      console.log(`🔍 开始处理商品 ${goods_id} 的出库明细`);

      // 插入出库明细记录
      const insertSql = 'INSERT INTO inventoryoutitem (out_id, goods_id, in_id, unit, price, quantity, amount, house_id, area_id, notes) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)';
      const insertParams = [out_id, goods_id, in_id, unit, price, quantity, calculated_amount, house_id, area_id, notes];

      console.log('📝 准备插入出库明细:', insertParams);
      const [insertResult] = await this.db.query(insertSql, insertParams);
      console.log('✅ 出库明细插入成功，insertId:', insertResult.insertId);

      // 查询同一goods_id在inventoryoutitem中的总数量
      const sumSql = 'SELECT SUM(quantity) AS total_quantity FROM inventoryoutitem WHERE goods_id = ?';
      const [[{ total_quantity }]] = await this.db.query(sumSql, [goods_id]);
      console.log(`📊 商品 ${goods_id} 累计出库数量已更新为:`, total_quantity || 0);

      // 查找或创建inventory记录，获取正确的stock_id
      const findInventorySql = 'SELECT stock_id, current_stock FROM inventory WHERE goods_id = ? AND house_id = ?';
      const [existingInventory] = await this.db.query(findInventorySql, [goods_id, house_id]);

      let stockId;
      let currentStock;
      if (existingInventory.length > 0) {
        // 库存记录存在，使用现有的stock_id和当前库存
        stockId = existingInventory[0].stock_id;
        currentStock = existingInventory[0].current_stock || 0;
        console.log('📋 使用现有库存记录，stock_id:', stockId, '当前库存:', currentStock);
      } else {
        // 库存记录不存在，创建新的库存记录
        const insertInventorySql = 'INSERT INTO inventory (goods_id, house_id, current_stock, safety_stock, status, notes) VALUES (?, ?, ?, ?, ?, ?)';
        const insertInventoryParams = [
          goods_id,
          house_id,
          0, // 初始库存设为0（因为是出库）
          0, // 安全库存默认为0
          '0', // 状态默认为正常
          `出库创建库存记录，出库单号: ${out_id}`
        ];
        const [insertInventoryResult] = await this.db.query(insertInventorySql, insertInventoryParams);
        stockId = insertInventoryResult.insertId;
        currentStock = 0;
        console.log('🆕 创建新库存记录，stock_id:', stockId);
      }

      // 计算新的库存余额
      const newBalance = Math.max(0, currentStock - quantity);
      console.log(`💰 库存计算: 当前库存 ${currentStock} - 出库数量 ${quantity} = 新余额 ${newBalance}`);

      // 更新库存记录的当前库存
      const updateInventorySql = 'UPDATE inventory SET current_stock = ?, updated_at = ? WHERE stock_id = ?';
      const updateInventoryParams = [newBalance, currentTime, stockId];
      await this.db.query(updateInventorySql, updateInventoryParams);
      console.log('🔄 库存记录更新成功');

      // 插入库存日志记录
      const logSql = 'INSERT INTO inventory_log (stock_id, goods_id, house_id, area_id, change_type, change_quantity, balance, user_id, related_order, change_time, notes) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)';
      const logParams = [
        stockId, // 使用正确的stock_id
        goods_id,
        house_id,
        area_id,
        'outbound',
        -quantity, // 出库为负数
        newBalance,
        user_id,
        related_order,
        currentTime,
        inventory_log_notes || `出库单${out_id} - 商品${goods_id}`
      ];

      console.log('📊 准备插入库存日志:', logParams);
      const [logResult] = await this.db.query(logSql, logParams);
      console.log('✅ 库存日志插入成功，详情结果:', logResult);

      // 查询刚刚插入的出库明细记录
      const lastInsertSql = 'SELECT * FROM inventoryoutitem WHERE item_id = ?';
      const [lastInsertResult] = await this.db.query(lastInsertSql, [insertResult.insertId]);

      // 返回结构化的结果
      const result = {
        success: true,
        message: '出库明细添加成功',
        data: {
          item_id: insertResult.insertId,
          out_id: out_id,
          goods_id: goods_id,
          quantity: quantity,
          amount: calculated_amount,
          stock_id: stockId,
          previous_stock: currentStock,
          new_balance: newBalance,
          total_outbound_quantity: total_quantity || 0
        },
        record: lastInsertResult[0] || { item_id: insertResult.insertId },
        metadata: {
          created_at: currentTime,
          change_type: 'outbound',
          inventory_updated: true
        }
      };

      console.log('🎉 出库明细处理完成:', result);
      return result;

    } catch (error) {
      console.error('❌ 添加出库明细失败:', error.message);

      // 特别处理唯一约束错误
      if (error.message.includes('Duplicate entry')) {
        console.log('🔄 发生唯一约束冲突，尝试自动生成新的area_id');

        // 获取当前最大的area_id值并加1
        const maxAreaIdSql = 'SELECT MAX(area_id) as max_id FROM inventoryoutitem WHERE out_id = ? AND goods_id = ?';
        const [maxResult] = await this.db.query(maxAreaIdSql, [out_id, goods_id]);
        const newAreaId = (maxResult[0].max_id || 0) + 1;

        console.log(`🔢 生成新的area_id: ${newAreaId}，重新尝试插入`);

        // 使用新的area_id重新调用此方法
        const retryParams = {
          ...params,
          area_id: newAreaId
        };

        return await this.addOutboundDetail(retryParams);
      }

      throw new Error(`出库明细操作失败: ${error.message}`);
    }
  }
}


module.exports = OutboundModel;
